package com.baoyouqun.mapper;

import com.baoyouqun.entity.SmsSendLimit;
import com.baoyouqun.entity.SmsVerification;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Optional;

@Mapper
public interface SmsMapper {

    /**
     * 保存验证码记录
     */
    @Insert("INSERT INTO sms_verification(phone, code, scene, send_time, expire_time, is_used) " +
            "VALUES(#{phone}, #{code}, #{scene}, #{sendTime}, #{expireTime}, 0)")
    void saveVerification(SmsVerification verification);

    /**
     * 查询未使用且未过期的验证码
     */
    @Select("SELECT * FROM sms_verification " +
            "WHERE phone = #{phone} AND scene = #{scene} AND is_used = 0 " +
            "AND expire_time > #{currentTime} " +
            "ORDER BY send_time DESC LIMIT 1")
    Optional<SmsVerification> findValidVerification(
            @Param("phone") String phone,
            @Param("scene") String scene,
            @Param("currentTime") LocalDateTime currentTime);

    /**
     * 标记验证码为已使用
     */
    @Update("UPDATE sms_verification SET is_used = 1 WHERE id = #{id}")
    void markAsUsed(@Param("id") Long id);

    /**
     * 查询当日发送限制
     */
    @Select("SELECT * FROM sms_send_limit WHERE phone = #{phone} AND send_date = #{sendDate}")
    Optional<SmsSendLimit> findSendLimit(@Param("phone") String phone, @Param("sendDate") LocalDate sendDate);

    /**
     * 新增发送限制记录
     */
    @Insert("INSERT INTO sms_send_limit(phone, send_date, send_count, last_send_time) " +
            "VALUES(#{phone}, #{sendDate}, 1, #{lastSendTime})")
    void insertSendLimit(SmsSendLimit limit);

    /**
     * 更新发送限制记录
     */
    @Update("UPDATE sms_send_limit SET send_count = send_count + 1, last_send_time = #{lastSendTime} " +
            "WHERE id = #{id}")
    void updateSendLimit(@Param("id") Long id, @Param("lastSendTime") LocalDateTime lastSendTime);
}
    